﻿using System;
using System.Collections.Generic;
using System.Linq;
using NewsPublish.Model.Entity;
using NewsPublish.Model.Request;
using NewsPublish.Model.Response;

namespace JT.WEB.Service
{
    //Banner 服务
    public class BannerService
    {
        private readonly ContextNews _db;
        public BannerService(ContextNews db)
        {
            this._db = db;
        }
        //添加Banner
        public ResponseModel AddBanner(AddBanner banner)
        {
            Banner ba = new Banner { AddTime = DateTime.Now, Image = banner.Image, Url = banner.Url, Remark = banner.Remark };
            _db.Banner.Add(ba);
            int i = _db.SaveChanges();
            if (i > 0)
            {
                return new ResponseModel { code = 200, result = "Banner添加成功" };
            }
            return new ResponseModel { code = 0, result = "添加失败" };
        }
        //获取 Banner 集合
        public ResponseModel GetBannerList()
        {
            IOrderedEnumerable<Banner> banners = _db.Banner.ToList().OrderByDescending(c => c.AddTime);
            ResponseModel response = new ResponseModel
            {
                code = 200,
                result = "Banner 集合获取 成功",
                data = new List<BannerModel>()
            };
            foreach (Banner banner in banners)
            {
                response.data.Add(new BannerModel
                {
                    Id = banner.Id,
                    Image = banner.Image,
                    Remark = banner.Remark,
                    Url = banner.Url,
                });
            }
            return response;
        }
        public ResponseModel DeleteBanner(int bannerId)
        {
            Banner banner = _db.Banner.Find(bannerId);
            if (banner == null)
            {
                return new ResponseModel { code = 0, result = "Banner不存在" };
            }
            _db.Banner.Remove(banner);
            int i = _db.SaveChanges();
            if (i > 0)
            {
                return new ResponseModel { code = 200, result = "Banner删除成功" };
            }
            return new ResponseModel { code = 0, result = "Banner删除失败" };

        }
    }
}
